package com.excel;

import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;

import com.excel.model.ExcelData;
import com.excel.util.CellUtils;

public class SampleKeyWorkdSearcher extends KeyWordSeacher {

	public SampleKeyWorkdSearcher(String path) {
		super(path);
	}

	@Override
	public ExcelData search(String keyword) {
		ExcelData  data = new ExcelData();
		Vector<Vector<Object>> rows = new Vector<Vector<Object>>();
		data.setData(rows);
		int columnCount = 0;
		int num = this.book.getNumberOfSheets();
		for (int i = 0; i < num; i++) {
			Sheet sheet = this.book.getSheetAt(i);
			if (sheet != null && sheet.getLastRowNum() != 0) {
				List<CellRangeAddress> cellRangeAddress = new ArrayList<CellRangeAddress>();
				CellUtils.getCombineCell(sheet, cellRangeAddress);
				int lastRowNum = sheet.getLastRowNum();
				for (int j = 1; j <= lastRowNum; j++) {
					Row r = sheet.getRow(j);
					if (r == null) {
						continue;
					}
					Vector<Object> rowData = new Vector<Object>();
					boolean flag = false;
					int lastCellNum = r.getLastCellNum();
					columnCount = (lastCellNum> columnCount)?lastCellNum:columnCount;
					for (int k = 0; k <= lastCellNum; k++) {
						Cell c = r.getCell(k);
						if (c == null) {
							rowData.add("");
							continue;
						}
						String value = "";
						if (cellRangeAddress.size() != 0) {
							CellRangeAddress address = CellUtils
									.getCombineRangeAddress(cellRangeAddress,
											c, sheet);
							if (address != null) {
								value = CellUtils.getStringValue(sheet.getRow(
										address.getFirstRow()).getCell(
										address.getFirstColumn()));
							}
						}
						if ("".equals(value)) {
							value = CellUtils.getStringValue(c);
						}

						rowData.add(value);
						if (!flag && value.contains(keyword)) {
							flag = true;
						}
					}
					if (flag) {
						rows.add(rowData);
					}
				}
			}
		}
		data.setColumnCount(columnCount);
		return data;
	}
}
